# lm() + step()
# maybe data transformation...

#setwd("Programming/R/projects/flu/")
setwd("projects/flu/")

# can add 'col.names=...'
train.set <- read.table("trainingSet.txt", header=F)
#train.set[1]#

# V49=distance
v49 <- lm(V49 ~ ., data=train.set)
v49.step <- step(v49)

summary(v49.step)
plot(train.set$V49, fitted.values(v49.step), xlab="antigen dist", 
  ylab="EADpred dist")

abline(0, 1, col="red")

##############################
# distance < 0 ...
train.set$V49[train.set$V49 < 0] <- 0

#pdf()

# use both 'xaxs' and 'yaxs'="i", and NO 'frame.plot=F' !
plot(train.set$V49, fitted.values(v49.step), xlab="antigen dist", 
  ylab="EADpred dist", main="Training set", xaxs="i", yaxs="i", xlim=c(0,5),
  ylim=c(0,5))
#axis(2, 1:4, col="yellow")

abline(0, 1, col="red")



# to PREDICT

pred.set.all <- read.table("predSet.txt", header=F)
#pred.set <- pred.set.all[, 1:48]
#pred.set[1,]

#pred.dist <- predict(v49.step, pred.set)
#hist(pred.dist)
#write.table(pred.dist, file="pred.dist.txt", sep="\n", row.names=F, col.names=F)

#pred.set.all <- cbind(pred.set.all, pred.dist)
#pred.set.all[1,]
#write.table(pred.set.all, file="pred.dist.all.txt", row.names=F, col.names=F)


SEP <- 2754
REP <- 70
dists <- rep(0, SEP)
pos <- 1

#for (i in 1:2)
for (i in 1:REP)
{
	#print(i)
	pos <- pos + (i - 1) * SEP
	#print(pos) #
	pred.set <- pred.set.all[pos:(pos + SEP - 1), ]
	#print(length(pred.set[,1])) #
	#print(dim(pred.set))
	#row.names(pred.set) <-  1:SEP #

	pred.dist <- predict(v49.step, pred.set[, 1:48])
	
	pred.dist <- as.vector(pred.dist) ########## IMPORTANT
	#print(length(pred.dist))
	#print(which(is.na(pred.dist)))#
	
	pred.dist[is.na(pred.dist)] <- 0  ##remove NA

	#print(dists[1]) #
	#print(pred.dist[1]) #
	dists <- dists + pred.dist
	print(dists[1])#
}
print(dists / REP)
dists <- dists / REP
unique(dists) #269

dists <- data.frame(pred.set.all[1:2754, 50], dists)

write.table(dists, file="dist_70.txt", row.names=F, col.names=F, quote=F)



